﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Common.Logging;
using InfoboardAdapterC.Common;
using InfoboardAdapterC.Connection;
using Microsoft.Win32;
using NKnife.IoC;

namespace InfoboardAdapterC.Parameter
{
    public class ParameterConfigViewModel
    {
        private readonly IniFileConfig _IniFile = DI.Get<IniFileConfig>();
        private readonly RegistryHelper _RegistryHelper = DI.Get<RegistryHelper>();
        private static readonly ILog _loggerLog = LogManager.GetLogger<ParameterConfigViewModel>();
        private const string Subkey = @"Software\Microsoft\Windows\CurrentVersion\Run";
        private readonly string _Name;

        public ParameterConfigViewModel()
        {
            var processes = Process.GetCurrentProcess();
            _Name = processes.ProcessName;
        }

        /// <summary>
        /// 保存服务端配置
        /// </summary>
        /// <param name="serviceIp"></param>
        /// <param name="servicePort"></param>
        public void SaveConfig(string serviceIp, string servicePort)
        {
            _IniFile.IniWriteValue(nameof(ParameterConfigViewModel), nameof(serviceIp), serviceIp);
            _IniFile.IniWriteValue(nameof(ParameterConfigViewModel), nameof(servicePort), servicePort);
        }
        /// <summary>
        /// 读取服务端配置
        /// </summary>
        /// <param name="serviceIp"></param>
        /// <param name="servicePort"></param>
        public void LoadConfig(out string serviceIp, out string servicePort)
        {
            serviceIp= _IniFile.IniReadValue(nameof(ParameterConfigViewModel), nameof(serviceIp));
            servicePort= _IniFile.IniReadValue(nameof(ParameterConfigViewModel), nameof(servicePort));
        }

        public void SetStarUpConfig()
        {
            var path = System.Windows.Forms.Application.ExecutablePath;
            if (_RegistryHelper.IsRegistryExist(Registry.LocalMachine, Subkey, _Name))
            {
                _RegistryHelper.DeleteRegist(Registry.LocalMachine, Subkey, _Name);
                _loggerLog.Info("清除原注册信息。");
            }
            _RegistryHelper.SetRegistryData(Registry.LocalMachine, Subkey, _Name, path);
            _loggerLog.Info("设置注册信息。");
        }

        public bool IsRegistryExist => _RegistryHelper.IsRegistryExist(Registry.LocalMachine, Subkey, _Name);

        public void RemoveStarUpConfig()
        {
            if (!_RegistryHelper.IsRegistryExist(Registry.LocalMachine, Subkey, _Name)) return;
            _RegistryHelper.DeleteRegist(Registry.LocalMachine, Subkey, _Name);
            _loggerLog.Info("清除原注册信息。");
        }
    }
}
